package PriorityQueue;

import java.util.Arrays;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        this.elem = new int[10];
    }

    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] =  array[i];
            usedSize++;
        }
        for (int parent = (usedSize-1-1)/2; parent>=0;parent--){
            shiftDown(parent,usedSize);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {//大根堆版
        int child = (root * 2) + 1;
        while(child<len){
            if(child+1<usedSize&&elem[child]<elem[child+1]){//比较左右孩子
                child++;
            }
            if (elem[child]>elem[root]){//检查父亲是否比孩子大
                swap(root,child);
                root = child;
                child = (child*2)+1;
            }else{//若已经满足大根堆，else执行break跳出向下调整的循环
                break;
            }
        }
    }

    private void swap(int a, int b){
        int temp = elem[a];
        elem[a] = elem[b];
        elem[b]=temp;
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            this.elem = Arrays.copyOf(elem,elem.length*2);
        }
        this.elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child-1)/2;
        while(child>0){
            if(elem[child]>elem[parent]){
                swap(child,parent);
                child=parent;
                parent = (parent-1)/2;
            }else{
                break;
            }
        }
    }

    private boolean isFull() {
        return usedSize==elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize==0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        return elem[0];
    }
}